package dz.chuxin.framework.widget.rowview;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import dz.chuxin.framework.util.DensityUtil;

/**
 * RowView分组容器
 * Created by chuxin on 2016/7/17.
 */
public class RowGroupView extends LinearLayout {

    private Context mContext;

    public RowGroupView(Context context) {
        this(context, null);
    }

    public RowGroupView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RowGroupView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setOrientation(VERTICAL);
        setBackgroundColor(Color.WHITE);
    }

    public void stuffData(RowViewGroupDescriptor groupDescriptor, OnRowClickListener listener) {
        if (groupDescriptor == null || groupDescriptor.getRowDescriptors().size() < 1) return;

        LayoutParams layoutParams = (LayoutParams) getLayoutParams();
        if (layoutParams == null)
            layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = DensityUtil.dp2px(mContext, groupDescriptor.getMarginTop());
        setLayoutParams(layoutParams);

        LayoutParams lineParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
        for (int i = 0; i < groupDescriptor.getRowDescriptors().size(); i++) {
            BaseRowDescriptor rowDescriptor = groupDescriptor.getRowDescriptors().get(i);
            BaseRowView rowView = null;
            if (rowDescriptor instanceof NormalRowDescriptor) {
                rowView = new NormalRowView(mContext);
            }
            if (rowView == null) continue;
            rowView.stuffData(rowDescriptor, listener);
            addView(rowView);
            // 不是最后一行View时添加分隔线
            if (i != groupDescriptor.getRowDescriptors().size() - 1) {
                View line = new View(mContext);
                line.setBackgroundResource(groupDescriptor.getDividerColor());
                lineParams.leftMargin = DensityUtil.dp2px(mContext, rowDescriptor.getHorizontalPadding());
                lineParams.rightMargin = DensityUtil.dp2px(mContext, rowDescriptor.getHorizontalPadding());
                addView(line, lineParams);
            }
        }
    }
}
